// 1. request /json/article_list.json
// 2. update dom tree
function renderAuthor(currentUser) {
    document.querySelector('.author-avatar').src = currentUser.avatar
    document.querySelector('.author-username').textContent = currentUser.username
    document.querySelector('.author-git').href = currentUser.gitRepo
}

function renderCount(articleCount, typeCount) {
    document.querySelector('.article-count').textContent = articleCount
    document.querySelector('.type-count').textContent = typeCount
}

function renderArticleList(articleList) {
    console.log(articleList)
    var container = document.querySelector('.articleList')
    console.log(container)
    for (var i in articleList) {
        var article = articleList[i]
        console.log(article)

        var html = `<div class="blog">` +
            `<div class="title">${article.title}</div>` +
            `<div class="date">${article.publishedAt}</div>` +
            `<div class="desc">${article.summary}</div>` +
            `<a href="blog_content.html?aid=${article.aid}" class="detail">查看全文 &gt;&gt;</a>` +
        `</div>`

        container.innerHTML += html
    }
    /*
    <div class="blog">
        <div class="title">我的第一篇博客</div>
        <div class="date">2021-06-02</div>
        <div class="desc">
            从今天起, 我要认真敲代码. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cum distinctio ullam eum ut
            veroab laborum numquam tenetur est in dolorum a sint, assumenda adipisci similique quaerat vel.
            Facere,
            et.
        </div>
        <a href="blog_content.html?blogId=1" class="detail">查看全文 &gt;&gt;</a>
    </div>
    */
}

var xhr = new XMLHttpRequest()
xhr.open('get', '/article-list.json')
xhr.onload = function() {
    alert(this.responseText);
    var data = JSON.parse(this.responseText)
    if (!data.currentUser) {
        // redirect
        //location = '/login.html'
        location.assign('/login.html')
        return
    }

    renderAuthor(data.currentUser)
    renderCount(data.articleCount, data.typeCount)
    renderArticleList(data.articleList)
}
xhr.send()